package test;

import io.netty.buffer.ByteBuf;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileInputDemo {
    static final String fileUrl = "C:\\Users\\Administrator\\Desktop\\test.txt";
    public static void main(String[] args) throws IOException {
        // 读取数据
        readData();
        // 写数据
        writeData();
    }

    private static void writeData() throws IOException {
        byte message[] = { 83, 111, 109, 101, 32, 98, 121, 116, 101, 115, 46 };
        FileOutputStream out = new FileOutputStream(fileUrl);
        // 获取FileChannel
        FileChannel channel = out.getChannel();
        // 分配ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 写入数据
        for(int i = 0;i<message.length;i++){
            byteBuffer.put(message[i]);
        }
        System.out.println("position = " + byteBuffer.position() + "；limit = " + byteBuffer.limit() + "；capacity = " + byteBuffer.capacity());
        byteBuffer.flip();
        System.out.println("position = " + byteBuffer.position() + "；limit = " + byteBuffer.limit() + "；capacity = " + byteBuffer.capacity());
        channel.write(byteBuffer);
        out.close();
    }

    private static void readData() throws IOException {
        FileInputStream in = new FileInputStream(fileUrl);
        // 获取FileChannel
        FileChannel fc = in.getChannel();
        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 读取数据到缓冲区，即向缓冲区中写数据
        fc.read(byteBuffer);
        // 切换到读模式
        byteBuffer.flip();
        // 读取数据并输出到控制台
        while(byteBuffer.remaining() > 0){
            byte b = byteBuffer.get();
            System.out.println((char)b);
        }
        fc.close();
    }

}
